import VueRouter from 'vue-router';
import Container from '@/pages/container/index.vue';
import routes from './routes';

export const getMicroRouteLocation = location => {
  const prefix = '/micros/paas-cli';

  if (typeof location === 'string' && !location.startsWith(prefix)) {
    location = prefix + location;
  } else if (typeof location === 'object' && location.path && !location.path.startsWith(prefix)) {
    location = {
      ...location,
      path: prefix + location.path
    };
  }

  console.log({ location });
  return location;
};

class MicroRouter {
  routes;

  constructor() {
    this.routes = routes;
  }

  /**
   * 注册路由实例
   */
  registerRouter() {
    const isMain = !!window.__POWERED_BY_QIANKUN__;

    const router = new VueRouter({
      scrollBehavior: () => ({ y: 0 }),
      routes: isMain ? this.getMicroRoutes() : this.routes
    });

    if (isMain) {
      // 挟持 router 跳转方法
      const originalRouterPush = router.push.bind(router);
      const originalRouterReplace = router.replace.bind(router);
      router.push = (...args) => originalRouterPush(getMicroRouteLocation(args[0]), ...args.slice(1));
      router.replace = (...args) => originalRouterReplace(getMicroRouteLocation(args[0]), ...args.slice(1));
    }

    return router;
  }

  /**
   * 获取微应用路由表
   */
  getMicroRoutes() {
    return [
      {
        path: '/micros/paas-cli',
        component: Container,
        // 作为 child route 不需要 / 前缀
        children: this.routes.map(route => ({
          ...route,
          path: route.path.startsWith('/') ? route.path.slice(1) : route.path
        }))
      }
    ];
  }
}

const microRouter = new MicroRouter();
export default microRouter;
